package com.jingdianjichi.wx.async;

import com.jingdianjichi.wx.ai.AnswerCache;
import com.jingdianjichi.wx.ai.SiliconFlowClient;
import com.jingdianjichi.wx.entity.PendingQuestion;
import com.jingdianjichi.wx.mapper.PendingQuestionMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
@Slf4j
public class AsyncAnswerWorker {

    @Resource private PendingQuestionMapper mapper;
    @Resource private SiliconFlowClient ai;
    @Resource private AnswerCache cache;

    // 每2秒拉一批待处理
    @Scheduled(fixedDelay = 2000)
    public void run() {
        try {
            List<PendingQuestion> list = mapper.pickBatch(10);
            for (PendingQuestion p : list) {
                try {
                    if (mapper.markProcessing(p.getId()) != 1) continue; // 抢占失败
                    String answer = ai.chatOnce(p.getQuestionText());
                    mapper.saveAnswer(p.getId(), answer, "auto");
                    cache.put(p.getQuestionKey(), answer, 300);
                    log.info("异步生成答案成功 id={}, qKey={}", p.getId(), p.getQuestionKey());
                } catch (Exception e) {
                    log.warn("异步生成答案失败 id={}, err={}", p.getId(), e.toString());
                    mapper.markFailed(p.getId(), e.toString());
                }
            }
        } catch (Exception e) {
            log.warn("定时任务异常: {}", e.toString());
        }
    }
}
